package org.finesys.common.core.support.concurrent;

import org.springframework.util.ObjectUtils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 并发线程名称设置
 */
public class NamedThreadFactory implements ThreadFactory {

	private final AtomicInteger poolNumber = new AtomicInteger(1);

	private final ThreadGroup threadGroup;

	private final AtomicInteger threadNumber = new AtomicInteger(1);

	private final String namePrefix;

	public NamedThreadFactory(String name) {
		SecurityManager securityManager = System.getSecurityManager();
		threadGroup = (securityManager != null) ? securityManager.getThreadGroup()
				: Thread.currentThread().getThreadGroup();
		if (ObjectUtils.isEmpty(name)) {
			name = "pool";
		}
		namePrefix = name + "-" + poolNumber.getAndIncrement() + "-thread-";
	}

	@Override
	public Thread newThread(Runnable r) {
		Thread t = new Thread(threadGroup, r, namePrefix + threadNumber.getAndIncrement(), 0);
		t.setDaemon(false);
		t.setPriority(Thread.NORM_PRIORITY);
		return t;
	}

}
